package com.example.his.api.db.dao;

import com.example.his.api.db.pojo.GoodsSnapshotEntity;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class GoodsSnapshotDao {
  @Resource
  private MongoTemplate mongoTemplate;
  
  public String hasGoodsSnapshot(String md5) {
    Criteria criteria = Criteria.where("md5").is(md5);
    Query query = new Query(criteria);
    query.skip(0);
    query.limit(1);
    GoodsSnapshotEntity entity = mongoTemplate.findOne(query, GoodsSnapshotEntity.class);
    return entity != null ? entity.get_id() : null;
  }
  
  public String insert(GoodsSnapshotEntity entity) {
    return mongoTemplate.save(entity).get_id();
  }
  
  public GoodsSnapshotEntity searchById(String id) {
    GoodsSnapshotEntity entity = mongoTemplate.findById(id, GoodsSnapshotEntity.class);
    return entity;
  }
  
  //  查询体检快照中的检查
  public List <Map> searchCheckup(String id, String sex) {
    Aggregation aggregation = Aggregation.newAggregation(Aggregation.project("checkup"), // 规定结果集的类名
        Aggregation.unwind("$checkup"), // 将checkup字段拆分为单独的文档
        Aggregation.match(Criteria.where("_id").is(id) // 定位快照记录
            //            筛选适合当前体检人性别的检查项目
            .and("checkup.sex").in("无", sex)));
    
    AggregationResults <HashMap> res = mongoTemplate.aggregate(aggregation, "goods_snapshot", HashMap.class);
    
    ArrayList list = new ArrayList <>();
    res.getMappedResults().forEach(item -> {
      System.out.println("item----------" + item.toString());
      HashMap map = (HashMap)item.get("checkup");
      list.add(map);
    });
    
    return list;
  }
  
  
}
